package com.xuan.yuapi.service.impl.inner;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xuan.common.model.entity.UserInterfaceInfo;
import com.xuan.common.service.InnerUserInterfaceInfoService;
import com.xuan.yuapi.common.ErrorCode;
import com.xuan.yuapi.exception.BusinessException;
import com.xuan.yuapi.service.UserInterfaceInfoService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 清凉茶
 * @description 针对表【user_interface_info】的数据库操作Service实现
 * @createDate 2024-05-22 10:39:32
 */

@DubboService
public class InnerUserInterfaceInfoServiceImpl implements InnerUserInterfaceInfoService {

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    /**
     *  统计接口调用次数
     * @param interfaceInfoId
     * @param userId
     * @return
     */

    @Override
    public boolean invokeCount(Long interfaceInfoId, Long userId) {
        return userInterfaceInfoService.invokeCount(interfaceInfoId, userId);
    }

    /**
     * 获取接口剩余调用次数
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public int getRestNum(Long interfaceInfoId, Long userId) {
        UserInterfaceInfo userInterfaceInfo = checkInterfaceInfoIsExist(interfaceInfoId, userId);
        return userInterfaceInfo.getLeftNum();
    }

    private UserInterfaceInfo checkInterfaceInfoIsExist(Long interfaceInfoId, Long userId) {
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 查看用户-接口关系表数据是否存在
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("interfaceInfoId", interfaceInfoId);
        queryWrapper.eq("userId", userId);
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoService.getOne(queryWrapper);
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return userInterfaceInfo;
    }
}




